package com.agileai.portal.controller.uui;

import java.util.Date;

import com.agileai.common.AppConfig;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.uui.UserLocalManage;
import com.agileai.portal.extend.uui.UserSyncHelper;
import com.agileai.portal.wsclient.uui.ResultStatus;
import com.agileai.portal.wsclient.uui.UserSync;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

public class UserActiveHandler
        extends BaseHandler {
    public UserActiveHandler() {
        super();
    }
    
	public ViewRenderer prepareDisplay(DataParam param){
		String userId = param.get("userId");
		String tokeId = param.get("tokenId");
		this.setAttributes(param);
		if (StringUtil.isNotNullNotEmpty(userId)){
			UserLocalManage userLocalManage = this.lookupService(UserLocalManage.class);
			DataRow row  = userLocalManage.retrieveUserRecord(userId);
			if (row != null && !row.isEmpty()){
				AppConfig appConfig = (AppConfig)this.lookupService("appConfig");
				String state = row.stringValue("USER_STATE");
				if ("1".equals(state)){
					this.setErrorMsg(userId + "账户已被激活！");	
				}else{
					String tempTokenId = row.getString("TOKEN_ID");
					if (tempTokenId != null && tempTokenId.equals(tokeId)){
						Date date = row.getTimestamp("TOKEN_TIME");
						Date curDate = new Date();
						long diffDay = DateUtil.getDateDiff(date, curDate, DateUtil.DAY);
						int ExpiredDays = appConfig.getIntConfig("UnifiedUserIntegrateConfig", "ExpiredDays");
						if (diffDay > ExpiredDays){
							if (resetToken8SendMail(row)){
								String mail = row.getString("USER_MAIL");
								this.setErrorMsg("激活URL已过期，生成账户新激活链接发至邮箱"+UserSyncHelper.genMaskedMail(mail));
							}else{
								this.setErrorMsg("激活URL已过期，生成账户新激活链接失败！");
							}
						}else{
							boolean result = updateUserStatus(userId);
							if (!result){
								this.setErrorMsg(userId + "激活失败！");		
							}else{
								String activeRedirectURL = appConfig.getConfig("UnifiedUserIntegrateConfig", "ActiveRedirectURL");
								this.setAttribute("activeRedirectURL",activeRedirectURL);
								
								Date storeTokenTime = new Date();
								userLocalManage.updateUserTokends(userId, "", storeTokenTime);
							}
						}
					}else{
						this.setErrorMsg("不合法的账户激活URL，请检查!");		
					}
				}
			}else{
				this.setErrorMsg(userId + "用户不存在,请确认!");
			}
		}else{
			this.setErrorMsg("激活链接以及参数不正确,请检查!");
		}
		return new LocalRenderer(getPage());
	}
	
	private boolean resetToken8SendMail(DataRow row){
		boolean result = false;
		try {
			UserSync userSync = UserSyncHelper.getUserSyncService();
			String tokenId = UserSyncHelper.genTokenId("sendMail");
			String mailAddress = row.stringValue("USER_MAIL");
			String userCode = row.stringValue("USER_CODE");
			String storeTokenId = String.valueOf(System.currentTimeMillis());
			String mailContent = UserSyncHelper.createRegistryMailContent(userCode, storeTokenId);
			String mailSubject = "账户激活链接";
			ResultStatus resultStatus = userSync.sendMail(tokenId, mailAddress,mailSubject,mailContent);
			if (resultStatus.isSuccess()){
				Date storeTokenTime = new Date();
				UserLocalManage userLocalManage = this.lookupService(UserLocalManage.class);
				userLocalManage.updateUserTokends(userCode, storeTokenId, storeTokenTime);
				result = true;				
			}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return result;
	}
	
	private boolean updateUserStatus(String userCode){
		boolean result = false;
		try {
			UserSync userSync = UserSyncHelper.getUserSyncService();
			String tokenId = UserSyncHelper.genTokenId("activeUser");
			userSync.activeUser(tokenId, userCode);
			
			UserLocalManage userLocalManage = this.lookupService(UserLocalManage.class);
			userLocalManage.updateUserStatus(userCode,"1");
			result = true;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return result;
	}
}